package com.duolebo.uteped_sdk;

import android.os.Handler;
import android.os.Looper;

import com.duolebo.uteped_sdk.utils.Const;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;

/**
 * @Author: LiuYang
 * @Date: 2023/12/11 12:26
 * @Description: 与flutter通信事件管理
 */
public class UTEPedEventHandler implements EventChannel.StreamHandler{

    private EventChannel eventChannel;
    private EventChannel.EventSink eventSink;
    private final Handler handler = new Handler(Looper.getMainLooper());

    public UTEPedEventHandler(BinaryMessenger binaryMessenger) {
        this.eventChannel = new EventChannel(binaryMessenger,Const.PUBLISH_EVENT);
        this.eventChannel.setStreamHandler(this);
    }

    public void publishEvent(Map<String, Object> map) {
        handler.post(() -> {
            if(eventSink != null)
                eventSink.success(map);
        });
    }

    public void publishFailed(String errorCode, String errMessage, Object errorDetails) {
        handler.post(() -> {
            if (eventSink != null) {
                eventSink.error(errorCode, errMessage, errorDetails);
            }
        });
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        this.eventSink = events;
    }

    @Override
    public void onCancel(Object arguments) {
        this.eventSink = null;
    }
}
